class LedModule {
  constructor(deviceId) {
    this.state = false; // 初始状态为关闭
    this.topic = 'device/led'; // LED控制主题
    this.stateTopic = 'device/led/state'; // LED状态发布主题
    this.deviceId = deviceId;
  }

  // 初始化LED模块
  async init(mqttConnector) {
    this.mqttConnector = mqttConnector;
    await this.mqttConnector.subscribe(this.topic);
    this.mqttConnector.onMessage(this.handleMessage.bind(this));
    console.log('LED模块已初始化');
  }

  // 处理接收到的消息
  handleMessage(topic, message) {
    if (topic === this.topic) {
      try {
        // 只处理JSON格式消息（已在mqtt-connector中解析）
        const command = message;
        if (command.type === 'control-command' && command.command) {
          if (command.command.action === 'turn-on') {
            this.turnOn();
          } else if (command.command.action === 'turn-off') {
            this.turnOff();
          } else if (command.command.action === 'toggle') {
            this.toggle();
          } else {
            console.log(`未知的LED命令: ${command.command.action}`);
          }
        } else {
          console.log(`无效的LED命令格式: ${JSON.stringify(message)}`);
        }
      } catch (error) {
        console.error(`处理LED命令错误: ${error.message}`);
      }
    }
  }

  // 打开LED
  turnOn() {
    this.state = true;
    console.log('LED已打开');
    this.publishState();
  }

  // 关闭LED
  turnOff() {
    this.state = false;
    console.log('LED已关闭');
    this.publishState();
  }

  // 切换LED状态
  toggle() {
    this.state = !this.state;
    console.log(`LED已${this.state ? '打开' : '关闭'}`);
    this.publishState();
  }

  // 发布LED状态
  async publishState() {
    const stateMessage = {
      deviceId: this.deviceId,
      timestamp: Date.now(),
      type: 'sensor-data',
      data: {
        value: this.state ? 'on' : 'off',
        status: 'normal'
      }
    };
    await this.mqttConnector.publish(this.stateTopic, JSON.stringify(stateMessage));
  }
}

module.exports = LedModule;